<?php
/**
 * Front Controller
 *  
 * @author Sean Crystal <seancrystal@gmail.com>
 * @package MVP-PHP
 */
require_once 'settings.php';
require_once 'components/exceptions/Exceptions.php';

session_start();

$mod  = ($_REQUEST['mod'] ? $_REQUEST['mod'] : $settings['defaultMod']);
$page = ($_REQUEST['page'] ? $_REQUEST['page'] : $settings['defaultPage']);

define(ROOT_DIR, dirname(__FILE__));
define(APP_DIR, ROOT_DIR .'/app');
define(LIB_DIR, ROOT_DIR .'/lib');
define(TEMPLATE_PREFIX, APP_DIR ."/{$mod}/templates/{$page}");

Redirect::$mod  = $mod;
Redirect::$page = $page;

$app = new Application($settings);

$pageFile = APP_DIR ."/{$mod}/{$page}.php";

if (!file_exists($pageFile)) {
	throw new PageNotFoundException($mod, $page);
}

require $pageFile;

// each /$mod/$page.php file should contain a Page object named $mod$pagePage
$pageClass = "{$mod}{$page}Page";

if (!(class_exists($pageClass))) {
	throw new ClassNotFoundException($pageClass);
}

// Start the app
$app->Go(new $pageClass, new Request($mod, $page, $_REQUEST['action'], $_REQUEST));


function __autoload($class)
{
	if (preg_match('/Presenter$/', $class)) {
		$filename = ROOT_DIR ."/components/presenters/{$class}.php";
	} elseif (preg_match('/View$/', $class)) {
		$filename = ROOT_DIR ."/components/views/{$class}.php";
	} elseif (preg_match('/Renderer$/', $class)) {
		$filename = ROOT_DIR ."/components/renderers/{$class}.php";
	} elseif (preg_match('/^i/', $class)) {
		$filename = ROOT_DIR ."/interfaces/{$class}.php"; 
	}
	
	if (file_exists($filename)) {
		require_once $filename;
	} elseif (file_exists(ROOT_DIR ."/components/{$class}.php")) {
		require_once ROOT_DIR ."/components/{$class}.php";
	}
}

?>